<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="73px">
          <el-form-item label="用户关键词" prop="userKeyword">
            <el-input v-model="queryParams.userKeyword" placeholder="请输入关键词" clearable style="width: 350px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <!-- <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item> -->

          <el-form-item>
            <el-button type="primary" icon="Search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" size="mini" @click="handleAdd"
              v-hasPermi="['user:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="EditPen" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['user:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['user:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
                  <el-button
                     type="info"
                     plain
                     icon="Upload"
                     @click="handleImport"
                     v-hasPermi="['user:import']"
                  >导入</el-button>
               </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="userId" label="ID" width="90" />
      <el-table-column prop="username" label="用户名" width="130" />
      <el-table-column prop="degree" label="学位" width="120" />
      <el-table-column prop="position" label="职称" width="120" />
      <el-table-column prop="post" label="职务" width="150" />
      <el-table-column prop="department" label="部门" width="230" />
      <!-- <el-table-column prop="quotaStandard" label="定额标准" width="100" /> -->
      <el-table-column prop="role" label="角色" />
    </el-table>

    <!-- 新增用户的对话框 -->
<el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
  <el-form ref="userForm" :model="formData" label-width="100px">
    <!-- 用户名和角色 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="用户名" prop="username" required>
          <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="角色" prop="role" required>
          <el-select v-model="formData.role" placeholder="请选择角色">
            <el-option label="普通用户" value="普通用户"></el-option>
            <el-option label="二级学院管理员" value="二级学院管理员"></el-option>
            <el-option label="超级管理员" value="超级管理员"></el-option>
          </el-select>
        </el-form-item>
     
      </el-col>
      
    </el-row>

    <!-- 学位和职称 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="学位" prop="degree" required>
          <el-select v-model="formData.degree" placeholder="请选择学位">
            <el-option label="博士" value="博士"></el-option>
            <el-option label="硕士" value="硕士"></el-option>
            <el-option label="学士" value="学士"></el-option>
            <el-option label="无" value="无"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="职称" prop="position" required>
          <el-select v-model="formData.position" placeholder="请选择职称" allow-create filterable>
            <el-option label="教授" value="教授"></el-option>
            <el-option label="副教授" value="副教授"></el-option>
            <el-option label="讲师" value="讲师"></el-option>
            <el-option label="高级工程师" value="高级工程师"></el-option>
            <el-option label="无" value="无"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 职务和定额标准 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="职务" prop="post" required>
          <el-input v-model="formData.post" placeholder="请输入职务"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="部门" prop="department" required>
          <el-select v-model="formData.department" placeholder="请选择部门">
            <el-option label="宝石与艺术设计学院" value="宝石与艺术设计学院"></el-option>
            <el-option label="外国语学院" value="外国语学院"></el-option>
            <el-option label="经济学院" value="经济学院"></el-option>
            <el-option label="机械与资源工程学院" value="机械与资源工程学院"></el-option>
            <el-option label="教师教育学院" value="教师教育学院"></el-option>
            <el-option label="大数据与软件工程学院" value="大数据与软件工程学院"></el-option>
            <el-option label="电子与信息工程学院" value="电子与信息工程学院"></el-option>
            <el-option label="文学与传媒学院" value="文学与传媒学院"></el-option>
            <el-option label="法学院" value="法学院"></el-option>
            <el-option label="马克思主义学院" value="马克思主义学院"></el-option>
            <el-option label="管理学院" value="管理学院"></el-option>
            <el-option label="食品与制药工程学院" value="食品与制药工程学院"></el-option>
            <el-option label="体育健康学院" value="体育健康学院"></el-option>
            <el-option label="无" value="无"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="定额标准" prop="quotaStandard" required>
          <el-input v-model="formData.quotaStandard" placeholder="请输入定额标准"></el-input>
        </el-form-item> -->
      </el-col>
    </el-row>

    <!-- 部门 -->
    <!-- <el-row>
      <el-col :span="25">
        <el-form-item label="部门" prop="department" required>
          <el-select v-model="formData.department" placeholder="请选择部门">
            <el-option label="宝石与艺术设计学院" value="宝石与艺术设计学院"></el-option>
            <el-option label="外国语学院" value="外国语学院"></el-option>
            <el-option label="经济学院" value="经济学院"></el-option>
            <el-option label="机械与资源工程学院" value="机械与资源工程学院"></el-option>
            <el-option label="教师教育学院" value="教师教育学院"></el-option>
            <el-option label="大数据与软件工程学院" value="大数据与软件工程学院"></el-option>
            <el-option label="电子与信息工程学院" value="电子与信息工程学院"></el-option>
            <el-option label="文学与传媒学院" value="文学与传媒学院"></el-option>
            <el-option label="法学院" value="法学院"></el-option>
            <el-option label="马克思主义学院" value="马克思主义学院"></el-option>
            <el-option label="管理学院" value="管理学院"></el-option>
            <el-option label="食品与制药工程学院" value="食品与制药工程学院"></el-option>
            <el-option label="体育健康学院" value="体育健康学院"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row> -->
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </template>
</el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
         <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
            drag
         >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <div class="el-upload__tip">
                     <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                  </div>
                  <span>仅允许导入xls、xlsx格式文件。</span>
               </div>
            </template>
         </el-upload>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFileForm">确 定</el-button>
               <el-button @click="upload.open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
<!-- 分页组件 -->
<Pagination v-model="queryParams" :total="total" @change="handleChange" />
    <el-footer>

    </el-footer>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { listUser, delUser, addUser, updateUser } from "@/api/user";
import { ElMessage, ElMessageBox } from 'element-plus';
import Pagination from '@/components/Pagination/index.vue';

const tableData = ref([]); // 初始化为响应式数组
const title = ref("");
const open = ref(false);
//处理选中行
const selectedRow = ref(null);

/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
};
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 上传的地址
  url: "http://localhost:8080/user/importData",
  // headers: {
  //   withCredentials: true
  // },
  // url: import.meta.env.VITE_APP_BASE_API + "/user/importData"
});

// 对话框相关变量
const dialogVisible = ref(false);
const dialogTitle = ref('新增用户');
const formData = reactive({
  userId: '',
  username: '',
  degree: '',
  position: '',
  post: '',
  department: '',
  quotaStandard: '',
  role: ''
});

// 定义查询参数
const queryParams = ref({
  userKeyword: '',
  currentPage: 1,
  pageSize: 10,
});
const total = ref(0);
// const queryParams = ref({
//   userKeyword: '',
// });

// 控制显示/隐藏搜索表单
const showSearch = ref(true);

// 单选和多选状态
const single = ref(false);
const multiple = ref(false);

const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true; // 开始上传时禁用按钮
};

const handleFileSuccess = (response, file, fileList) => {
  upload.isUploading = false; // 上传完成后启用按钮
  if (response.code === 200) {
    ElMessage.success("导入成功");
    upload.open = false; // 关闭对话框
    getUserList(); // 刷新用户列表
  } else {
    ElMessage.error(response.message || "导入失败，请检查文件格式或内容");
  }
};

// 查询方法
async function handleQuery() {
  try {
    console.log('发送请求，参数:', {
      ...queryParams.value,
      currentPage: queryParams.value.currentPage,
      pageSize: queryParams.value.pageSize
    });

    const response = await listUser({
      ...queryParams.value,
      currentPage: queryParams.value.currentPage,
      pageSize: queryParams.value.pageSize
    });

    console.log('接收到的响应:', response);

    // 更新表格数据
    tableData.value = response.data;
    total.value = response.total;

    console.log('表格数据已更新:', tableData.value);
  } catch (error) {
    console.error('查询失败:', error);
  }
}

// 重置查询条件
function resetQuery() {
  queryParams.value = {
    userKeyword: ''
  };
  handleQuery(); // 重置后重新查询
}

// 显示新增对话框
function handleAdd() {
  // 清空表单数据
  Object.assign(formData, {
    username: '',
    degree: '',
    position: '',
    post: '',
    department: '',
    quotaStandard: '',
    role: ''
  });
  dialogTitle.value = '新增用户';
  dialogVisible.value = true;
}

// 提交表单到后端
async function handleSubmit() {
  try {

    if (formData.userId) { // 如果存在id，则为修改操作
      const sendData = {
        userId: formData.userId,
        username: formData.username,
        degree: formData.degree,
        position: formData.position,
        post: formData.post,
        department: formData.department,
        quotaStandard: formData.quotaStandard,
        role: formData.role
      };
     await updateUser(sendData); // 调用API进行更新操作
      ElMessage({
        message: '修改成功',
        type: 'success'
      });
    } else { // 否则为新增操作
      // const sendData = {
      //   username: formData.username,
      //   degree: formData.degree,
      //   position: formData.position,
      //   post: formData.post,
      //   department: formData.department,
      //   quotaStandard: formData.quotaStandard,
      //   role: formData.role
      // };
      await addUser(formData);
      ElMessage({
        message: '新增成功',
        type: 'success'
      });
    }

    dialogVisible.value = false; // 关闭对话框
    await handleQuery(); // 刷新列表以显示新添加/修改的记录
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请重试');
  }
}

function handleSelectionChange(selection) {
  if (selection.length > 0) {
    single.value = selection.length !== 1;
    multiple.value = false; // 当有选择时，允许删除
    selectedRow.value = selection;
  } else {
    single.value = true;
    multiple.value = true; // 没有选择时，不允许删除
    selectedRow.value = null;
  }
}

//修改
async function handleUpdate() {
  if (!selectedRow.value) {
    ElMessage.error('请选择一条记录进行修改');
    return;
  }
  // 将选中的行数据赋值给formData
  if (selectedRow.value.length > 0) {
    Object.assign(formData, selectedRow.value[0]);
  }
  // 将选中的行数据赋值给formData
  // Object.assign(formData, JSON.parse(JSON.stringify(selectedRow.value)));

  dialogTitle.value = '修改用户';
  dialogVisible.value = true;
}

//删除
async function handleDelete() {
  if (!selectedRow.value || selectedRow.value.length === 0) {
    ElMessage.error('请选择一条或多条记录进行删除');
    return;
  }

  try {
    const selectedIds = selectedRow.value.map(row => Number(row.userId)); // 确保 ID 是数字

    console.log('Selected IDs:', selectedIds); // 调试信息

    await ElMessageBox.confirm(
      '是否确认删除用户编号为"' + selectedIds.join('", "') + '"的数据项？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 调用删除 API
    await delUser(selectedIds);

    // 提示删除成功
    ElMessage({
      message: '删除成功',
      type: 'success'
    });

    // 刷新列表以显示最新的更改
    await handleQuery();

    // 清除选中状态
    selectedRow.value = [];
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败，请重试');
    }
  }
}


const handleChange = (newPage, newPageSize) => {
    queryParams.value.currentPage = newPage;
    queryParams.value.pageSize = newPageSize;
    handleQuery();
};

// 页面加载时自动查询一次
onMounted(() => {
  handleQuery();
});

</script>

<style scoped>
.el-input__inner {
  margin-left: 2px;
}
</style>